/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.rbac.service.grant.impl;

import com.je.common.base.DynaBean;
import com.je.common.base.service.CommonService;
import com.je.common.base.service.MetaService;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.rbac.service.grant.RbacGrantTopMenuPermissionService;
import com.je.rbac.service.permission.GrantMethodEnum;
import com.je.rbac.service.permission.GrantTypeEnum;
import com.je.rbac.service.permission.template.TopMenuDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;

@Service
public class RbacGrantTopMenuPermissionServiceImpl implements RbacGrantTopMenuPermissionService {

    @Autowired
    private MetaService metaService;
    @Autowired
    private CommonService commonService;
    @Autowired
    private TopMenuDataService topMenuDataService;

    @Override
    public List<Map<String, Object>> findUserTopMenuPermissions(String userId) {
        return metaService.selectSql(ConditionsWrapper.builder().table("JE_RBAC_VUSERPERM")
                .eq("JE_RBAC_USER_ID",userId)
                .eq("USERPERM_GRANTTYPE_CODE",GrantTypeEnum.TOPMENU.name()));
    }

    @Override
    public void updateTopMenuSeeUsers(String menuCode, List<String> userIdList) {
        DynaBean permBean = topMenuDataService.writeTopMenuShowPermission(menuCode, true);
        saveUserPermAssocaition(userIdList, permBean);
    }

    @Override
    public void removeTopMenuSeeUsers(String menuCode, List<String> userIdList) {
        String permCode = topMenuDataService.formatTopMenuShowTemplate(menuCode);
        DynaBean permBean = metaService.selectOne("JE_RBAC_PERM",ConditionsWrapper.builder().eq("PERM_CODE",permCode));
        if(permBean != null){
            metaService.delete("JE_RBAC_USERPERM",ConditionsWrapper.builder().eq("JE_RBAC_PERM_ID",permBean.getStr("JE_RBAC_PERM_ID"))
                    .notIn(userIdList != null && !userIdList.isEmpty(),"JE_RBAC_USER_ID",userIdList));
        }

    }

    @Override
    public void updateTopMenuSeeRoles(String menuCode, List<String> roleIdList) {
        DynaBean permBean = topMenuDataService.writeTopMenuShowPermission(menuCode, true);
        saveRolePermAssocaition(roleIdList, permBean);
    }

    @Override
    public void removeTopMenuSeeRoles(String menuCode, List<String> roleIdList) {
        String permCode = topMenuDataService.formatTopMenuShowTemplate(menuCode);
        DynaBean permBean = metaService.selectOne("JE_RBAC_PERM",ConditionsWrapper.builder().eq("PERM_CODE",permCode));
        if(permBean != null){
            metaService.delete("JE_RBAC_ROLEPERM",ConditionsWrapper.builder().eq("JE_RBAC_PERM_ID",permBean.getStr("JE_RBAC_PERM_ID"))
                    .notIn(roleIdList != null && !roleIdList.isEmpty(),"JE_RBAC_ROLE_ID",roleIdList));
        }
    }

    @Override
    public void updateTopMenuSeeDepts(String menuCode, List<String> deptIdList) {
        DynaBean permBean = topMenuDataService.writeTopMenuShowPermission(menuCode, true);
        saveDeptPermAssocaition(deptIdList, permBean);
    }

    @Override
    public void remoeveTopMenuSeeDepts(String menuCode, List<String> deptIdList) {
        String permCode = topMenuDataService.formatTopMenuShowTemplate(menuCode);
        DynaBean permBean = metaService.selectOne("JE_RBAC_PERM",ConditionsWrapper.builder().eq("PERM_CODE",permCode));
        if(permBean != null){
            metaService.delete("JE_RBAC_DEPTPERM",ConditionsWrapper.builder().eq("JE_RBAC_PERM_ID",permBean.getStr("JE_RBAC_PERM_ID"))
                    .notIn(deptIdList != null && !deptIdList.isEmpty(),"JE_RBAC_DEPARTMENT_ID",deptIdList));
        }
    }

    @Override
    public void updateTopMenuSeeOrgs(String menuCode, List<String> orgIdList) {
        DynaBean permBean = topMenuDataService.writeTopMenuShowPermission(menuCode, true);
        saveOrgPermAssocaition(orgIdList, permBean);
    }

    @Override
    public void removeTopMenuSeeOrgs(String menuCode, List<String> orgIdList) {
        String permCode = topMenuDataService.formatTopMenuShowTemplate(menuCode);
        DynaBean permBean = metaService.selectOne("JE_RBAC_PERM",ConditionsWrapper.builder().eq("PERM_CODE",permCode));
        if(permBean != null){
            metaService.delete("JE_RBAC_ORGPERM",ConditionsWrapper.builder().eq("JE_RBAC_PERM_ID",permBean.getStr("JE_RBAC_PERM_ID"))
                    .notIn(orgIdList != null && !orgIdList.isEmpty(),"JE_RBAC_ORG_ID",orgIdList));
        }
    }

    /**
     * 保存机构关系
     *
     * @param userIdList
     * @param permissionBean
     */
    private void saveUserPermAssocaition(List<String> userIdList, DynaBean permissionBean) {
        //查询已存在的关联关系
        List<DynaBean> associationList = metaService.select("JE_RBAC_USERPERM", ConditionsWrapper.builder()
                .eq("USERPERM_GRANTTYPE_CODE", GrantTypeEnum.TOPMENU.name())
                .in("JE_RBAC_USER_ID", userIdList)
                .eq("JE_RBAC_PERM_ID", permissionBean.getStr("JE_RBAC_PERM_ID")));
        List<String> havedUserPermissionList = new ArrayList<>();
        for (DynaBean eachAssociationBean : associationList) {
            havedUserPermissionList.add(eachAssociationBean.getStr("JE_RBAC_USER_ID"));
        }
        //写入关联关系
        DynaBean userPermBean;
        for (String eachUserId : userIdList) {
            //如果已包含从关联关系，则不做任何操作
            if (havedUserPermissionList.contains(eachUserId)) {
                continue;
            }
            userPermBean = new DynaBean("JE_RBAC_USERPERM", false);
            userPermBean.set("JE_RBAC_USER_ID", eachUserId);
            userPermBean.set("JE_RBAC_PERM_ID", permissionBean.getStr("JE_RBAC_PERM_ID"));
            //授权方式
            userPermBean.set("USERPERM_TYPE_CODE", GrantMethodEnum.USER.name());
            userPermBean.set("USERPERM_TYPE_NAME", GrantMethodEnum.USER.getDesc());
            //授权类型
            userPermBean.set("USERPERM_GRANTTYPE_CODE", GrantTypeEnum.TOPMENU.name());
            userPermBean.set("USERPERM_GRANTTYPE_NAME", GrantTypeEnum.TOPMENU.getDesc());
            //todo 设置租户信息
            commonService.buildModelCreateInfo(userPermBean);
            metaService.insert(userPermBean);
            havedUserPermissionList.add(eachUserId);
        }
    }

    /**
     * 保存机构关系
     *
     * @param orgIdList
     * @param permissionBean
     */
    private void saveOrgPermAssocaition(List<String> orgIdList, DynaBean permissionBean) {
        //查询已存在的关联关系
        List<DynaBean> associationList = metaService.select("JE_RBAC_ORGPERM", ConditionsWrapper.builder()
                .eq("ORGPERM_GRANTTYPE_CODE", GrantTypeEnum.TOPMENU.name())
                .in("JE_RBAC_ORG_ID", orgIdList)
                .eq("JE_RBAC_PERM_ID", permissionBean.getStr("JE_RBAC_PERM_ID")));
        List<String> havedOrgPermissionList = new ArrayList<>();
        for (DynaBean eachAssociationBean : associationList) {
            havedOrgPermissionList.add(eachAssociationBean.getStr("JE_RBAC_ORG_ID"));
        }
        //写入关联关系
        DynaBean rolePermBean;
        for (String eachOrgId : orgIdList) {
            //如果已包含从关联关系，则不做任何操作
            if (havedOrgPermissionList.contains(eachOrgId)) {
                continue;
            }
            rolePermBean = new DynaBean("JE_RBAC_ORGPERM", false);
            rolePermBean.set("JE_RBAC_ORG_ID", eachOrgId);
            rolePermBean.set("JE_RBAC_PERM_ID", permissionBean.getStr("JE_RBAC_PERM_ID"));
            rolePermBean.set("ORGPERM_EXCLUDE_CODE", "0");
            rolePermBean.set("ORGPERM_EXCLUDE_NAME", "否");
            //授权方式
            rolePermBean.set("ORGPERM_TYPE_CODE", GrantMethodEnum.ROLE.name());
            rolePermBean.set("ORGPERM_TYPE_NAME", GrantMethodEnum.ROLE.getDesc());
            //授权类型
            rolePermBean.set("ORGPERM_GRANTTYPE_CODE", GrantTypeEnum.TOPMENU.name());
            rolePermBean.set("ORGPERM_GRANTTYPE_NAME", GrantTypeEnum.TOPMENU.getDesc());
            //todo 设置租户信息
            commonService.buildModelCreateInfo(rolePermBean);
            metaService.insert(rolePermBean);
            havedOrgPermissionList.add(eachOrgId);
        }
    }

    /**
     * 保存部门关系
     *
     * @param deptIdList
     * @param permissionBen
     */
    private void saveDeptPermAssocaition(List<String> deptIdList, DynaBean permissionBen) {
        List<DynaBean> associationList = metaService.select("JE_RBAC_DEPTPERM", ConditionsWrapper.builder()
                .eq("DEPTPERM_GRANTTYPE_CODE", GrantTypeEnum.TOPMENU.name())
                .in("JE_RBAC_DEPARTMENT_ID", deptIdList)
                .eq("JE_RBAC_PERM_ID", permissionBen.getStr("JE_RBAC_PERM_ID")));
        List<String> havedDeptPermissionList = new ArrayList<>();
        for (DynaBean eachAssociationBean : associationList) {
            havedDeptPermissionList.add(eachAssociationBean.getStr("JE_RBAC_DEPARTMENT_ID"));
        }

        //写入关联关系
        DynaBean rolePermBean;
        for (String eachDeptId : deptIdList) {
            if (havedDeptPermissionList.contains(eachDeptId)) {
                continue;
            }
            rolePermBean = new DynaBean("JE_RBAC_DEPTPERM", false);
            rolePermBean.set("JE_RBAC_DEPARTMENT_ID", eachDeptId);
            rolePermBean.set("JE_RBAC_PERM_ID", permissionBen.getStr("JE_RBAC_PERM_ID"));
            rolePermBean.set("DEPTPERM_EXCLUDE_CODE", "0");
            rolePermBean.set("DEPTPERM_EXCLUDE_NAME", "否");
            //授权方式
            rolePermBean.set("DEPTPERM_TYPE_CODE", GrantMethodEnum.ROLE.name());
            rolePermBean.set("DEPTPERM_TYPE_NAME", GrantMethodEnum.ROLE.getDesc());
            //授权类型
            rolePermBean.set("DEPTPERM_GRANTTYPE_CODE", GrantTypeEnum.TOPMENU.name());
            rolePermBean.set("DEPTPERM_GRANTTYPE_NAME", GrantTypeEnum.TOPMENU.getDesc());
            //todo 设置租户信息
            commonService.buildModelCreateInfo(rolePermBean);
            metaService.insert(rolePermBean);
            havedDeptPermissionList.add(eachDeptId);
        }
    }

    /**
     * 保存角色关系
     *
     * @param roleIdList
     * @param permissionBean
     */
    private void saveRolePermAssocaition(List<String> roleIdList, DynaBean permissionBean) {
        //查询已存在的关联关系
        List<DynaBean> associationList = metaService.select("JE_RBAC_ROLEPERM", ConditionsWrapper.builder()
                .eq("ROLEPERM_GRANTTYPE_CODE", GrantTypeEnum.TOPMENU.name())
                .in("JE_RBAC_ROLE_ID", roleIdList)
                .eq("JE_RBAC_PERM_ID", permissionBean.getStr("JE_RBAC_PERM_ID")));
        List<String> havedRolePermissionList = new ArrayList<>();
        for (DynaBean eachAssociationBean : associationList) {
            havedRolePermissionList.add(eachAssociationBean.getStr("JE_RBAC_ROLE_ID"));
        }
        //写入关联关系
        DynaBean rolePermBean;
        for (String eachRoleId : roleIdList) {
            //如果是正常权限，不是排他权限，则不做任何处理，如果是排他权限，则需要设置ROLEPERM_NOT_CHECKED
            if (havedRolePermissionList.contains(eachRoleId)) {
                continue;
            }

            rolePermBean = new DynaBean("JE_RBAC_ROLEPERM", false);
            rolePermBean.set("JE_RBAC_ROLE_ID", eachRoleId);
            rolePermBean.set("JE_RBAC_PERM_ID", permissionBean.getStr("JE_RBAC_PERM_ID"));
            rolePermBean.set("ROLEPERM_EXCLUDE_CODE", "0");
            rolePermBean.set("ROLEPERM_EXCLUDE_NAME", "否");
            //授权方式
            rolePermBean.set("ROLEPERM_TYPE_CODE", GrantMethodEnum.ROLE.name());
            rolePermBean.set("ROLEPERM_TYPE_NAME", GrantMethodEnum.ROLE.getDesc());
            //授权类型
            rolePermBean.set("ROLEPERM_GRANTTYPE_CODE", GrantTypeEnum.TOPMENU.name());
            rolePermBean.set("ROLEPERM_GRANTTYPE_NAME", GrantTypeEnum.TOPMENU.getDesc());
            //todo 设置租户信息
            commonService.buildModelCreateInfo(rolePermBean);
            metaService.insert(rolePermBean);
            havedRolePermissionList.add(eachRoleId);
        }
    }

}
